#include "MultiTimer.h"
#include <stdio.h>
#include <stdint.h>
#include <stdbool.h>
#include <stddef.h>

static MultiTimer* timerList = NULL;
static PlatformTicksFunction_t platformTicksFunction = NULL;

int multiTimerInstall(PlatformTicksFunction_t ticksFunc) {
    if (ticksFunc == NULL) {
        return -1; // Indicate error if ticksFunc is NULL
    }
    platformTicksFunction = ticksFunc;
    return 0;
}

static void removeTimer(MultiTimer* timer) {
    MultiTimer** current = &timerList;
    while (*current) {
        if (*current == timer) {
            *current = timer->next;
            break;
        }
        current = &(*current)->next;
    }
}

static bool is_unsigned_less(uint32_t a, uint32_t b)
{
    if (b >= a) {
        return true;
    } else {
        if ((a - b) < 0x7fffffff) {
            return false;
        } else {
            return true;
        }
    }
}

int multiTimerStart(MultiTimer* timer, uint32_t timing, MultiTimerCallback_t callback, void* userData) {
    if (!timer || !callback || platformTicksFunction == NULL) {
        return -1; // Return error if any parameter is invalid
    }

    removeTimer(timer); // Centralize removal logic

    timer->deadline = platformTicksFunction() + timing;
    timer->callback = callback;
    timer->userData = userData;

    MultiTimer** current = &timerList;
//    while (*current && ((*current)->deadline < timer->deadline)) {
    while (*current && is_unsigned_less((*current)->deadline, timer->deadline)) {
        current = &(*current)->next;
    }
    timer->next = *current;
    *current = timer;

    return 0;
}

int multiTimerStop(MultiTimer* timer) {
    removeTimer(timer); // Use centralized removal function
    return 0;
}

// g_sys_tick may overflow after about 50 min
static bool is_deadline_reached(uint32_t curr, uint32_t dead)
{
    if (curr >= dead) {
        if ((curr - dead) < 0x7fffffff) {
            // normal case
            return true;
        } else {
            // in the case that deadline overflows
            return false;
        }
    } else {
        if ((dead - curr) < 0x7fffffff) {
            // normal case
            return false;
        } else {
            // in the case that current overflows
            return true;
        }
    }
}

int multiTimerYield(void) {
    if (platformTicksFunction == NULL) {
        return -1; // Indicate error if platformTicksFunction is NULL
    }
//    uint32_t currentTicks = platformTicksFunction();
//    while (timerList && (currentTicks >= timerList->deadline)) {
    while (timerList && is_deadline_reached(platformTicksFunction(), timerList->deadline)) {
        MultiTimer* timer = timerList;
        timerList = timer->next; // Remove expired timer

        if (timer->callback) {
            timer->callback(timer, timer->userData); // Execute callback
        }
    }
//    return timerList ? (int)(timerList->deadline - currentTicks) : 0;
    return 0;
}
